<?php
defined('SYSPATH') or die('No direct script access.') ;
/**
  * @author Y.N
 *  2011/8/16
 */
class Cli_Goods extends CLI
{
	public function main()
	{
		$page = $this->args->page;
		if ($page)
		{
			// 清理已删除商品
			self::clean_goods($page);
		}else {
			// 清理已删除商品
			self::clean_goods();
			// 清理重复spu数据
			self::clean_aggregate();

			// 清理不规则产品
			self::fix_product();

			// 清理不规则商品
			self::fix_goods();
			// 清理价格属性
			self::fix_price();

			// 清理重复图片
			self::clean_picture();
		}

	}


	/**
	 * 清理重复spu数据
	 *
	 * @param	none
	 * @return	void
	 * @update	2011/8/26
	 */
	public static function clean_aggregate()
	{
		// 产品图片处理
		$ids = DB::select('id')
			->from('aggregate_prop')
			->group_by('sid')
			->group_by('name')
			->having(DB::expr('count(*)'), '>', 1)
			->order_by('id', 'desc')
			->fetch_all();
		if ( ! empty($ids))
		{
			DB::delete('aggregate_prop')
				->where('id', 'in', $ids)
				->execute();
		}
		CLI::output("\nSPU聚合数据删除完毕...");
	}

	/**
	 * 清理已删除的商品关联数据
	 *
	 * @param	none
	 * @return	void
	 * @update	2011/8/16
	 */
	public static function clean_goods($shop_id = NULL)
	{
		$select = DB::select('goods_id')
			->from('goods');

		if ( ! empty($shop_id))
		{
			$select->where('shop_id', '=', $shop_id);
		}else{
			$select->where('deleted', '=', 1);
		}
		$goods = $select->fetch_all();
		foreach ($goods as $g)
		{
			// 删除留言数据
			DB::delete('goods_leave_message')
				->where('goods_id', '=', $g['goods_id'])
				->execute();
			// 删除类目数据
			DB::delete('goods_cat_values')
				->where('goods_id', '=', $g['goods_id'])
				->execute();
			// 删除推荐数据
			DB::delete('goods_commends')
				->where('goods_id', '=', $g['goods_id'])
				->execute();
			if ($shop_id)
			{
				// 删除属性数据
				DB::delete('goods_props')
					->where('goods_id', '=', $g['goods_id'])
					->execute();
				// 删除属性数据
				DB::delete('goods_images')
					->where('goods_id', '=', $g['goods_id'])
					->execute();
				// 删除扩展数据
				DB::delete('goods_fields')
					->where('goods_id', '=', $g['goods_id'])
					->execute();
			}
		}
		if ($shop_id)
		{
			DB::delete('goods')
				->where('shop_id', '=', $shop_id)
				->execute();
		}
	}

	/**
	 * 清理重复图片数据
	 *
	 * @param	none
	 * @return	void
	 * @update	2011/8/16
	 */
	public static function clean_picture()
	{
		// 产品图片处理
		$ids = DB::select('id')
			->from('product_imgs')
			->group_by('product_id')
			->group_by('image_md5')
			->where('image_md5', 'is not', NULL)
			->having(DB::expr('count(*)'), '>', 1)
			->fetch_all();
		if ( ! empty($ids))
		{
			DB::delete('product_imgs')
				->where('id', 'in', $ids)
				->execute();
		}
		CLI::output("\n产品重复图片删除完毕...");
	}


	/**
	 * 修正不规整产品
	 *
	 * @param	none
	 * @return	void
	 * @update	2011/8/16
	 */
	public static function fix_product()
	{
		$update = array();

		/* 整理不规则产品 */
		$products = DB::select( 'product_id', 'props', 'binds')
			->from('products')
			->where('props', 'REGEXP', '[0-9]+;[0-9]+;')
			->or_where('binds', 'REGEXP', '[0-9]+;[0-9]+;')
			->fetch_all();
		foreach ($products as $p)
		{
			if (preg_match('/[0-9]+;[0-9]+;/', $p['props']))
			{
				$props_arr = explode(';', $p['props']);
				$update['props'] = self::handle_props($props_arr);
			}

			if (preg_match('/[0-9]+;[0-9]+;/', $p['binds']))
			{
				$binds_arr = explode(';', $p['binds']);
				$update['binds'] = self::handle_props($binds_arr);
			}

			DB::update('products')
				->set($update)
				->where('product_id', '=', $p['product_id'])
				->execute();
		}
		CLI::output("\n不规则产品整理完毕...");
	}

	/**
	 * 处理不规则属性字串
	 *
	 * @param	array props
	 * @return	void
	 * @update	2011/8/16
	 */
	public static function handle_props($props)
	{
		$string = "";
		foreach ($props as $k => $v)
		{
			// 是否为第一个数值
			if ($k)
			{
				// 是否为奇数值
				if (($k+1)%2==0)
				{
					$s = ":";
				} else {
					$s = ";";
				}
			} else {
				$s = "";
			}
			$string = $string.$s.$v;
		}
		return $string;
	}

	/**
	 * 更新不规则商品
	 *
	 * @param	none
	 * @return	void
	 * @update	2011/8/16
	 */
	public static function fix_goods()
	{
		$select = DB::select(DB::expr('distinct(goods_id)'))
			->from('goods_props')
			->where('props', 'REGEXP', '^[0-9]+$')
			->or_where('props', 'REGEXP', '[0-9]+;')
			->or_where('props', 'REGEXP', '[0-9]+:[0-9]+:');

		$iterator = new Db_Iterator($select, 'default', 10);
		$new_array = array();
		CLI::output("开始更新商品...\n");
		while ($iterator->valid())
		{
			foreach ($iterator->current() as $g)
			{
				if ( ! empty($g))
				{
					$goods = DB::select('goods_id', 'props', 'product_id')
						->from('goods')
						->where('goods_id', '=', $g['goods_id'])
						->where('deleted', '=', 0)
						->where('on_sale', '=', 1)
						->fetch_row();

					if ( ! empty($goods['product_id']))
					{
						$product = DB::select('props', 'binds')
							->from('products')
							->where('product_id', '=', $goods['product_id'])
							->fetch_row();

						$new_array[] = $product['props'];
						$new_array[] = $product['binds'];
						$props = implode(';', $new_array);

						unset($new_array);

						DB::update('goods')
							->set(array('props' => $props))
							->where('goods_id', '=', $goods['goods_id'])
							->execute();
					}else {
					    $props = $goods['props'];
					}

					$props_array = explode(';', $props);

					DB::delete('goods_props')
						->where('goods_id', '=', $g['goods_id'])
						->execute();

					foreach ($props_array as $k => $p)
					{
						if ( ! empty($p) AND strstr($p, ':'))
						{
							if (substr_count($p, ':') >=2)
							{
								continue;
							}
							$row = array(
								'goods_id' => $g['goods_id'],
								'props' => $p
							);
							DB::replace('goods_props', $row)->execute();
						}
					}
					CLI::output("商品ID".$g['goods_id']."更新成功...\n");
				}
			}
			$iterator->next();
		}
		CLI::output("更新完毕...");
	}

	/**
	 * 修正价格属性
	 *
	 * @param	none
	 * @return	void
	 * @update	2011/8/16
	 */
	public function fix_price()
	{
		// 修正价格属性
		$price_prop = DB::select('pid', 'cid')
			->from('item_props_view')
			->where('name_alias', 'like', '%价格%')
			->where('is_price_prop', '=', 0)
			->where('is_enum_prop', '=', 1)
			->where('is_key_prop', '=', 0)
			->fetch_all();
		foreach ($price_prop as $p)
		{
			$price_value = DB::select('*')
				->from('item_values_view')
				->where('cid', '=', $p['cid'])
				->where('pid', '=', $p['pid'])
				->fetch_all();

			// 价格处理
			foreach ($price_value as $v)
			{
				if (stristr($v['name_alias'], '以上'))
				{
					$min_price = (int) $v['name_alias'];
					$max_price = 0;
				}elseif (stristr($v['name_alias'], '以下'))
				{
					$min_price = 0;
					$max_price = (int) $v['name_alias'];
				}elseif (stristr($v['name_alias'], '-')) {
					$explode = explode('-', $v['name_alias']);
					$min_price = (int) current($explode);
					$max_price = (int) end($explode);
				}
				if (isset($min_price))
				{
					// 查找是否已存在
					$count = DB::select(DB::expr('count(*)'))
						->from('item_prop_prices')
						->where('vid', '=', $v['vid'])
						->fetch_one();
					if ( ! $count)
					{
						$insert = array(
							'vid' => $v['vid'],
							'min_price' => $min_price,
							'max_price' => $max_price,
						);
						DB::insert('item_prop_prices', array_keys($insert))
							->values(array_values($insert))
							->execute();
					}
				}
			}

			// 更新为价格属性
			DB::update('item_cat_props')
				->set(array('is_price_prop' => 1))
				->where('cid', '=', $p['cid'])
				->where('pid', '=', $p['pid'])
				->execute();

			CLI::output(">");
		}
		CLI::output("\n修正价格属性结束...");
	}
}